import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";

import BxjUpload from "@/components/BxjUpload";
import type { FormItemProps } from "../utils/types";
import { getKeyList, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { getAllRoleList } from "@/api/system";
import { getQuarterList } from "@/api/bxj/system";
import {
  getStarPage,
  updateStarStatus,
  saveOrUpdateStar,
  deleteStar,
  deleteBatchStar,
  uploadAvatar
} from "@/api/bxj/star";
import { ElMessageBox } from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    name: "",
    des: "",
    status: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编号",
      prop: "id",
      width: 90
    },
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="avator"
          preview-teleported={true}
          src={row.avatar || userAvatar}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "档期",
      prop: "schedule",
      minWidth: 90
    },
    {
      label: "描述",
      prop: "des",
      minWidth: 90,
      width: 666
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });

  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>明星吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        updateStarStatus(row)
          .then(() => {
            // 请求成功后更新状态
            // row.status = row.status === 0 ? 1 : 0; // 切换状态
            message("已成功修改明星状态", {
              type: "success"
            });
          })
          .catch(() => {
            // 请求失败后恢复状态
            row.status = row.status === 0 ? 1 : 0;
            message("修改明星状态失败", {
              type: "error"
            });
          })
          .finally(() => {
            // 请求完成后取消加载状态
            switchLoadMap.value[index] = {
              ...switchLoadMap.value[index],
              loading: false
            };
          });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleUpdate(row) {
  }

  function handleDelete(row) {
    deleteStar(row)
    .then(() => {
      message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
      onSearch();
    })
    .catch(() => {
      message(`操作失败`, {
        type: "error"
      });
    })
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deleteBatchStar(getKeyList(curSelected, "id"))
    .then(() => {
      message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    })
    .catch(() => {
      message(`操作失败`, {
        type: "error"
      });
    })
  }

  async function onSearch() {
   
    loading.value = true;
    const { result } = await getStarPage({
      ...toRaw(form), // 展开 form 中的内容
      currentPage: pagination.currentPage, // 当前页码
      pageSize: pagination.pageSize
    });
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.pageSize;
    pagination.currentPage = result.currentPage;


      loading.value = false;

  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    // form.deptId = "";
    // treeRef.value.onTreeReset();
    onSearch();
    
  };

  function onTreeSelect({ id, selected }) {
    // form.deptId = selected ? id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    console.log(row)
    addDialog({
      title: `${title}明星信息`,
      props: {
        formInline: {
          title,
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          // name: row?.name ?? "",
          des: row?.des ?? "",
          status: row?.status ?? 0,
          parentId: row?.parentId ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了明星名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        if (Array.isArray(curData.parentId)) {
          curData.schedule = curData.parentId.join(",");
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            saveOrUpdateStar(curData)
            .then(() => {
              chores();
            })
            .catch((res) => {
              message(JSON.parse(res.request.response).errMessage, {
                type: "error"
              });
              done(); // 关闭弹框
              onSearch();
            });
          }
        });
      }
    });
  }
  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "上传头像",
      width: "40%",
      closeOnClickModal: true,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(BxjUpload, {
          ref: cropRef,
          imgSrc: row.avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
        console.log("裁剪后的图片信息：", avatarInfo.value.base64);
        console.log(row)
        uploadAvatar(row.id, avatarInfo.value.base64)
        .then(response => {
          console.log("删除成功", response);
        })
        .catch(error => {
          console.error("删除失败", error);
        }).finally(() => {
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        })
      },
      closeCallBack: () => {
        // console.log("点击了取消")
        // cropRef.value.hidePopover();
      }
    });
  }
  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    // 归属部门
    const { result } = await getQuarterList();
    higherDeptOptions.value = handleTree(result);
    treeLoading.value = false;

    // 角色列表
    roleOptions.value = (await getAllRoleList()).data;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
